package sshFile;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;


public class readXml {
    public static void main(String[] args) throws Exception {
    	
    	
    	Map<String,String> pathdata=new HashMap<>();
        File f1=new File("C:\\huawutongji\\config.txt");
        InputStreamReader in = new InputStreamReader(new FileInputStream(f1),"UTF-8");
       
       BufferedReader bf = new BufferedReader(in);     
        String s=null;
           while((s = bf.readLine())!=null){
                if(s.startsWith("rootpath")){
                    String rootpath = s.split("=")[1].trim();
                    pathdata.put("rootpath", rootpath);
                }else if(s.startsWith("lspath")){
                    String lspath = s.split("=")[1].trim();
                    pathdata.put("lspath", lspath);
                }else if(s.startsWith("esnpath")){
                    String esnpath = s.split("=")[1].trim();
                    pathdata.put("esnpath", esnpath);
                }else if(s.startsWith("orderpath")){
                    String orderpath = s.split("=")[1].trim();
                    pathdata.put("orderpath", orderpath);
                }
                
                
                
                }
            bf.close();
    	
    	
        String a = pathdata.get("rootpath");
        int b = a.length();
        String c = a.substring(0,b-4);
        int d = c.length();
        try {
            ZipUncompress(a,c);
            } catch (Exception e) {
            e.printStackTrace();
        }
        

           Map<String,String> esn_name=new HashMap<>();
        
       
        List<String> filelist = getFileNmae(c,"Index.xml");
        for (String name : filelist) {
        	String node = getNode(c, name);
        	esn_name.put(node, name);
		}    
            
     
        File file = new File(c);
        delAllFile(file);
            
         Map<String, String> ne_ip = getdata(pathdata.get("lspath"));
         
         
         Map<String, String> esn_ne = getEsn(pathdata.get("esnpath"));
         
         List<NEBean> list=new  ArrayList<NEBean>();
         for (String esn : esn_name.keySet()) {
			String filename=esn_name.get(esn);
			
			if(esn_ne.containsKey(esn)){
				String ne = esn_ne.get(esn);
				if(ne_ip.containsKey(ne)){
					NEBean nebean=new NEBean();
					nebean.setNename(ne);
					nebean.setFilename(filename);
					nebean.setIp(ne_ip.get(ne));
					list.add(nebean);
				}
				
			}
		}
         try {
         File order=new File(pathdata.get("orderpath"));
     	 Writer ps = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(order), "UTF-8"));
     	 for (NEBean neBean : list) {
     	 ps.write("REG NE:IP=\""+neBean.getIp()+"\";"+"\r\n");	
     	 ps.write("INS LICENSE: DIR=\"/ftproot/RosenseLicense\", FN=\""+neBean.getFilename()+"\", FLG=NO, MODE=IPV4, IP=\"132.225.250.5\", USR=\"ftpuser\", PWD=\"Changeme_123\";"+"\r\n");		 
 		}
			
		
		ps.flush();
		ps.close();
        
         }catch(Exception e){
        	 e.printStackTrace();
         }
      
         
    }

    /*
     * 获取文件名字
     */
    
    public static List<String>  getFileNmae(String path,String filename){
    	 List<String> list = new ArrayList<>();
    	try{
    	//1.创建Reader对象
        SAXReader reader = new SAXReader();
        //2.加载xml
        Document document = reader.read(new File(path+"//"+filename));
        //3.获取根节点
        Element rootElement = document.getRootElement();
        Iterator iterator = rootElement.elementIterator();
       

        while (iterator.hasNext()) {
            Element stu = (Element) iterator.next();
            List<Attribute> attributes = stu.attributes();
            for (Attribute attribute : attributes) {
                String aaa = attribute.getName();
                if (aaa.equals("name")){
                    list.add(attribute.getValue());
                }
            }
        }
        
        }catch(Exception e){
        	e.printStackTrace();
        	
        }
		return list;
    }
  
    public static String  getNode(String path,String filename){
    	 String node="";
    	try{
    	//1.创建Reader对象
        SAXReader reader = new SAXReader();
        //2.加载xml
        Document document = reader.read(new File(path+"//"+filename));
        //3.获取根节点
        Element rootElement = document.getRootElement();
       
        Element element2 = rootElement.element("Header");
        
        Element element3 = element2.element("NodeInfo");
        Element elements4 = element3.element("ESN");
       
         node = elements4.getText();
        
       
        }catch(Exception e){
        	e.printStackTrace();
        	
        }
		return node;
    }
    
    
    public static  Map<String,String> getEsn(String path){   	
    	Map<String,String> map=new HashMap<>();
    	      
  		try {
  			File file=new File(path);
  		  BufferedReader bf = new BufferedReader(new FileReader(file));      
          String s=null;
           int count=0;
          while((s = bf.readLine())!=null){
         		count++;
          		if(count==1){
          			continue;
          		}
   	
        		  String[] sp = s.split("\\s+");                        
                  map.put(sp[1],sp[0]);
        	 
         
              }
          bf.close();   
    	
    	
    }catch(Exception e){
    	e.printStackTrace();
    }
		return map;
    
    }
    
    
    
    public static  Map<String,String> getdata(String path){   	
    	Map<String,String> map=new HashMap<>();
    	      
  		try {
  			File file=new File(path);
  		  BufferedReader bf = new BufferedReader(new FileReader(file));      
          String s=null;
           int count=0;
          while((s = bf.readLine())!=null){
        	 
        
          		count++;
          if(count>=12){
        		 if(s!=null && !"".equals(s) && !s.startsWith("---")){
        			
                     String[] sp = s.split("\\s+");
                   map.put(sp[1], sp[2]);
                  
             	}
        	
          }
           	 
    		         		
          
         
              }
          bf.close();   
    	
    	
    }catch(Exception e){
    	e.printStackTrace();
    }
		return map;
    
    }
    
    
    public static void ZipUncompress(String inputFile,String destDirPath) throws Exception {
        File srcFile = new File(inputFile);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        //开始解压
        //构建解压输入流
        ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile));
        ZipEntry entry = null;
        File file = null;
        while ((entry = zIn.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                file = new File(destDirPath, entry.getName());
                if (!file.exists()) {
                    new File(file.getParent()).mkdirs();//创建此文件的上级目录
                }
                OutputStream out = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(out);
                int len = -1;
                byte[] buf = new byte[1024];
                while ((len = zIn.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }
                // 关流顺序，先打开的后关闭
                bos.close();
                out.close();
            }
        }
    }

    public static void delAllFile(File directory){
        if (!directory.exists()){
            System.exit(0);

        }


        if (!directory.isDirectory()){
            directory.delete();
        } else{
            File [] files = directory.listFiles();

            // 空文件夹
            if (files.length == 0){
                directory.delete();
                return;
            }

            // 删除子文件夹和子文件
            for (File file : files){
                if (file.isDirectory()){
                    delAllFile(file);
                } else {
                    file.delete();
                }
            }

            // 删除文件夹本身
            directory.delete();
        }
    }




}

